package com.nbst.comnutil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import com.nbst.model.api.Print;
import com.nbst.model.api.PrintModel;

import org.springframework.stereotype.Component;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * @author wl
 * @ClassName: FileUtils
 * @Description:打印文件工具类
 * @date 2021年4月15日
 */
@Component
public class FileUtils {

    /**
     * 修改报表文件
     * 
     * @param list
     * @return
     */
    public static String replaceFile(PrintModel printModel, String newStr) {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        String fileUrl = null;
        try {
            // 创建 FileReader对象和FileWriter对象.
            String fileName = printModel.getFileName();
            String localurl = printModel.getLocalUrl();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDateTime time = LocalDateTime.now(ZoneOffset.of("+8"));
            String dir = time.format(formatter);
            Long file = time.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            File dirs = new File(localurl + dir);
            if (!dirs.exists()) {
                dirs.mkdirs();
            }
            fileUrl =  dir + "\\" + file + ".grf";
            // 创建 输入、输入出流对象.
            reader = new BufferedReader (new InputStreamReader (new FileInputStream(localurl + fileName),"UTF-8"));
            writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (localurl + fileUrl),"UTF-8"));
            String line = null;
            StringBuffer sbf = new StringBuffer();
            // 循环读取并追加字符
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }
            /* 替换内容 */

            String newString = sbf.toString();
            if (newStr != null) {
                String[] strs = newStr.split(",");
                for (int i = 0; i < strs.length; i++) {
                    newString = newString.replace("tihuanchaxun"+i, strs[i]);
                }
            }
            newString = newString.replace("#serverUrl", printModel.getServerUrl());
            writer.write(newString); // 写入文件
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭 reader 和 writer.
            try {
                if (reader != null)
                    reader.close();
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileUrl;
    }

    /**
     * 打印
     * 
     * @param url
     * @param fileName
     * @param newStr
     * @param Preview
     * @return
     */
    public static NormalResult toPrint(PrintModel printModel, String newStr,String Preview,String clientip) {
        NormalResult normalResult = new NormalResult();
        String url = printModel.getUrl();
        String reportUrl = replaceFile(printModel,newStr);
        Print print = new Print(reportUrl.substring(reportUrl.indexOf("\\")+1),url + reportUrl,Preview);
        print.setMethod("printreport");
        print.setReportType("gridreport");
        print.setToken("aa");
        JSONObject jasn = JSONUtil.parseObj(print);
        String result = HttpRequest.post("http://"+clientip+":"+12345+"/")
        .header("Content-Type","application/x-www-form-urlencoded")
        .header("dataType","json")
        .header("xhrFields","{withCredentials: false}")
        .header("crossDomain","true")
        .body(jasn.toString())
        .execute()
        .body();
        JSONObject jr = JSONUtil.parseObj(result);
        
        if("ok".equals(jr.get("status"))){
            normalResult.setCode(Constants.DefaultResultEnums.SYSTEM_NORMAL.getCode());
            normalResult.setMessage(Constants.DefaultResultEnums.SYSTEM_NORMAL.getName());
        }

        return normalResult;
    }
}
